﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AP.Framework.Infrastructure.Repositories.IRepositories;
using AP.Framework.Infrastructure.Entities;
using System.ComponentModel.DataAnnotations;
using ApCMS.Areas.Admin.Models;

namespace ApCMS.Areas.Admin.Controllers
{
    public class DefaultController : Controller
    {
        IUsers _users;
        IParam _param;
        public DefaultController(IUsers users, IParam param)
        {
            _users = users;
            _param = param;
        }

        public ActionResult Index()
        {
            if (Session["UserName"] != null)
            {
                sys_Param model = _param.GetAll().SingleOrDefault();
                if (model != null)
                {
                    Session["SiteName"] = model.SiteName;
                    Session["CompanyName"] = model.CompanyName;
                    Session["CompanyLog"] = model.CompanyLog;
                    Session["CopyRight"] = model.CopyRight;
                }
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Default", new { area = "Admin" });
            }           
        }
        public ActionResult LogOn()
        {
            return View();
        }
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    sys_Users users = _users.GetAll().Where(p => p.UserName == model.UserName  && p.Password == model.Password).FirstOrDefault();
                    if (users != null)
                    {
                        Session["UserName"] = users.UserName;
                        Session["PassWord"] = users.Password;
                        return RedirectToAction("Index", "Default", new { area = "Admin" });
                    }
                    else
                    {
                        ModelState.AddModelError("", "输入的用户名或密码不正确。");
                    }
                }
                catch (Exception)
                {

                    ModelState.AddModelError("", "登录出现错误。");
                }

            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }
    }
   
}
